﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Dict;
using Dict.DataModel;

namespace UI
{
    public class UIHeroLogic :MonoBehaviour
    {
        #region UIHero
        public UIHero hero;
        #endregion

        #region model height
        public int module0Height = 0;//属性
        public int module1Height = 0;//突破
        public int module2Height = 0;//技能
        public int module3Height = 0;//天赋
        public int module4Height = 0;//羁绊
        public int module5Height = 0;//远征技能
        
        public int currentModuleStartPos=0;
        #endregion

        #region Top label
        public GameObject heroNameText;
        public GameObject heroNameProportyText;
        public GameObject heroAptitudeText;
        public GameObject heroQualityText;
        public GameObject heroSpaceText;
        public GameObject hero2DTexture;
        #endregion

        #region Right
        public GameObject scrollView;
        public GameObject scrollBar;
        //属性
        public GameObject module0;
        

        //突破
        public GameObject module1;

        public GameObject breakThroughLevelText;//Lv 12
        public GameObject breakThroughDescribeText;//描述
        //技能
        public GameObject module2;
        public UIHeroSkillIcon[] skillIcons;

        //羁绊
        public GameObject module3;

        public GameObject luckGrid;
        public GameObject luckTemplete;
        #region 数据
        public List<UIHeroLuck> lucks;
        #endregion

        //天赋
        public GameObject module4;

        public GameObject talentGrid;
        public GameObject talentTemplete;

        //描述
        public GameObject heroDescribeText;

        //远征
        public GameObject module5;
        public UILabel expeditionLabel;
        #endregion

        #region Left Bottom
        public GameObject heroLevel;
        public GameObject heroIntelligence;
        public GameObject heroAttack;
        public GameObject heroLife;
        public GameObject heroMagicDefend;
        public GameObject heroPhysicsDefend;
        #endregion

        #region 按钮
        public GameObject switchBtn;
        public GameObject unloadBtn;//卸载英雄btn
        public GameObject bothBtns;

        public GameObject optBtnZone;//操作按钮区 
        public GameObject mainHero;
        public GameObject normalHero;
        #endregion

        UIHeroFormation battleHero=null;

        bool isMine;

        public void SetHero(bool showSwitchHero= true, bool showUnloadHero = true, bool showOptBtn = true, bool isMainHero = true)
        {
            optBtnZone.SetActive(showOptBtn);

            switchBtn.SetActive(false);
            unloadBtn.SetActive(false);
            bothBtns.SetActive(false);
            
            
            if (showSwitchHero && showUnloadHero)
            {
                bothBtns.SetActive(true);
            }
            else if (showSwitchHero)
            {
                switchBtn.SetActive(true);
            }
            else if (showUnloadHero)
            {
                unloadBtn.SetActive(true);
            }


            mainHero.SetActive(isMainHero);
            normalHero.SetActive(!isMainHero);

            LowHeroCard();
        }

        void LowHeroCard()
        {
            if (hero != null && 
                hero.heroData != null && 
                hero.heroData.quality <= (int)QualityValue.GREEN)
            {
                optBtnZone.SetActive(false);
                switchBtn.SetActive(false);
                unloadBtn.SetActive(false);
                bothBtns.SetActive(false);
            }

            if(battleHero!=null && 
               battleHero.hero!=null && 
               battleHero.hero.heroData!=null && 
               battleHero.hero.heroData.quality <= (int)QualityValue.GREEN)
            {
                optBtnZone.SetActive(false);
                switchBtn.SetActive(false);
                unloadBtn.SetActive(false);
                bothBtns.SetActive(false);
            }
        }

        public void Init(UIHeroFormation hero)
        {
            scrollBar.GetComponent<UIScrollBar>().value = 0;
            this.hero = hero.hero;

            lucks = hero.lucks;
            isMine = true;

            battleHero = hero;
            FillData(true);

            LowHeroCard();
        }

        public void Init(UIHero hero,bool isMine)
        {
            scrollBar.GetComponent<UIScrollBar>().value = 0;
            this.hero = hero;

            #region 添加临时的缘分
            List<TableYuan> luckDatas = Dict.DictDataManager.Instance.tableYuanDao.GetByOneIndex(this.hero.heroId);
            lucks = new List<UIHeroLuck>();
            foreach (var luck in luckDatas)
            {
                UIHeroLuck ul = new UIHeroLuck(luck, this.hero);
                ul.FreshLuckActived();
                lucks.Add(ul);
            }
            #endregion
            this.isMine = isMine;
            FillData(false);

            LowHeroCard();
        }
        
        void FillData(bool fHero)
        {
            #region 右边属性
            SetModuleOpenOrClose();

            FillTopData();
            FillPropertyData(hero, battleHero, fHero);

            FillBreakThroughData(hero.breachlevel);
            FillSkillData(hero.Skills);
            
            FillLucksData(lucks);
            FillTalentData(hero.TalentData);
           
            FillHeroDescribeData(TableTextBlo.GetText(hero.heroData.desc));

            FillExpeditionData();

            //重新定位每个模块的高度
            SetModuleHeight();
            #endregion
        }

        private void SetModuleOpenOrClose( )
        {
            //属性
            module0.SetActive(true);

            //突破
            module1.SetActive( true );

            var skillOpen = hero.Skills != null 
                && hero.Skills.Length > 0 
                && hero.Skills[0] != null
                && hero.Skills[1] != null; 
            //&& hero.Skills[2] != null;

            if(hero.Skills[2] != null)
            {
                module2Height = 522;
            }
            else
            {
                module2Height = 347;
            }

            //技能
            module2.SetActive( skillOpen );
            //羁绊
            module3.SetActive( lucks.Count > 0 );
            //天赋
            module4.SetActive(hero.TalentData.Count > 0 );
            //远征技能
            module5.SetActive(!string.IsNullOrEmpty(hero.heroData.expeditionSkill));
        }

        private void SetModuleHeight()
        {
            currentModuleStartPos=0;
            if(module0.activeSelf)
            {
                module0.transform.localPosition = new Vector3(0, -currentModuleStartPos, 0);
                currentModuleStartPos += module0Height;
            }

            if( module1.activeSelf )
            {
                module1.transform.localPosition = new Vector3( 0, -currentModuleStartPos, 0 );
                currentModuleStartPos+= module1Height;
            }

            if(module2.activeSelf)
            {
                module2.transform.localPosition = new Vector3( 0, -currentModuleStartPos, 0 );
                currentModuleStartPos+=module2Height;
                
            }

            if(module3.activeSelf)
            {
                module3.transform.localPosition = new Vector3( 0, -currentModuleStartPos, 0 );
                currentModuleStartPos+=module3Height;

            }

            if(module4.activeSelf)
            {
                module4.transform.localPosition = new Vector3( 0, -currentModuleStartPos, 0 );
                currentModuleStartPos+=module4Height;
            }

            if(module5.activeSelf)
            {
                module5.transform.localPosition = new Vector3(0, -currentModuleStartPos, 0);
                currentModuleStartPos += module5Height;
            }
        }

        public void FillTopData()
        {
            this.heroNameText.GetComponent<UILabel>().text = CommonMethod.GetHeroName(hero.heroId);
            string strIcon = hero.heroData.iconName.Replace("hero_icon_", "hero_2d_");
            AssetLoadHelper.Instance.SetTextureAsync(hero2DTexture.GetComponent<UITexture>(), "hero2d/" + strIcon,false);
            //this.hero2DTexture.GetComponent<UITexture>().mainTexture = Resources.Load<Texture>("hero2d/" + strIcon);
            this.heroNameProportyText.GetComponent<UILabel>().text = hero.talentLevel != 0 ? "+" + hero.talentLevel + "" : "";
            this.heroAptitudeText.GetComponent<UILabel>().text = hero.heroData.quality + "";
            this.heroQualityText.GetComponent<UILabel>().text = "[" + FontColor.Get(hero.heroData.quality) + "]" + TableTextBlo.GetText("quality_name_" + hero.heroData.quality) + "[-]";
            this.heroSpaceText.GetComponent<UILabel>().text = "" + hero.GetHeroSpaceName() + "";
        }

        public void FillPropertyData(UIHero hero, UIHeroFormation FormationHero,bool isBattleHero)
        {

            /**
              //战斗属性
            heroAttack.text = ((int)formation.GetPorp(AttributeQueue.Attack)).ToString();
            heroPdef.text = ((int)formation.GetPorp(AttributeQueue.PhyDefend)).ToString();
            heroHp.text = ((int)formation.GetPorp(AttributeQueue.Hp)).ToString();
            heroMdef.text = ((int)formation.GetPorp(AttributeQueue.MagicDefend)).ToString();
            */


            this.heroLevel.GetComponent<UILabel>().text = hero.level + "";
            this.heroIntelligence.GetComponent<UILabel>().text = hero.heroData.quality + "";


            if (isBattleHero)
            {
                this.heroAttack.GetComponent<UILabel>().text = ((int)battleHero.GetPorp(AttributeQueue.Attack)).ToString();
                this.heroPhysicsDefend.GetComponent<UILabel>().text = ((int)battleHero.GetPorp(AttributeQueue.PhyDefend)).ToString();
                this.heroLife.GetComponent<UILabel>().text = ((int)battleHero.GetPorp(AttributeQueue.Hp)).ToString();
                this.heroMagicDefend.GetComponent<UILabel>().text = ((int)battleHero.GetPorp(AttributeQueue.MagicDefend)).ToString();
            }
            else
            {
                this.heroAttack.GetComponent<UILabel>().text = (int)hero.GetPorp(AttributeQueue.Attack) + "";
                this.heroLife.GetComponent<UILabel>().text = (int)hero.GetPorp(AttributeQueue.Hp) + "";
                this.heroPhysicsDefend.GetComponent<UILabel>().text = (int)hero.GetPorp(AttributeQueue.PhyDefend) + "";
                this.heroMagicDefend.GetComponent<UILabel>().text = (int)hero.GetPorp(AttributeQueue.MagicDefend) + "";
            }
        }



        /// <summary>
        /// 填充突破数据
        /// </summary>
        private void FillBreakThroughData(int level)
        {
            breakThroughLevelText.GetComponent<UILabel>().text = TableTextBlo.GetText("level")+level;
        }
        
        /// <summary>
        /// 填充技能数据
        /// </summary>
        private void FillSkillData(UISkill[] skills)
        {
            if (module2.activeSelf)
            {
                int i = 0;
                foreach (var skill in skills)
                {
                    if (skill != null)
                    {
                        skillIcons[i].gameObject.SetActive(true);
                        skillIcons[i].Init(skill, hero.breachlevel, i++);
                    }
                    else
                        skillIcons[i].gameObject.SetActive(false);
                }
            }
        }


        List<GameObject> luckLs = new List<GameObject>();

        /// <summary>
        /// 填充羁绊数据(缘分数据)
        /// </summary>
        private void FillLucksData( List<UIHeroLuck> lucks )
        {
            if (module3.activeSelf)
            {
                if (lucks.Count > 0)
                {
                    if (luckLs.Count > 0)
                    {
                        foreach (var obj in luckLs)
                        {
                            GameObject.DestroyImmediate(obj);
                        }

                        luckLs.Clear();
                    }

                    luckGrid.GetComponent<UnfixedGrid>().ResetGrid();

                    const int topHeight = 49;

                    module3Height = topHeight;

                    int tCount = lucks.Count;

                    for (int i = 0; i < tCount; i++)
                    {

                        GameObject obj = GameObject.Instantiate(luckTemplete) as GameObject;
                        obj.SetActive(true);
                        obj.transform.SetParent(luckGrid.transform);
                        obj.transform.localScale = Vector3.one;
                        luckLs.Add(obj);

                        var Luck = lucks[i];

                        var luckInst = obj.GetComponent<UIHeroLuckTemplete>();

                        luckInst.Init(Luck.luckData.id, Luck.IsActived && isMine);

                        module3Height += luckInst.Height;
                        module3Height += luckGrid.GetComponent<UnfixedGrid>().Padding;

                        luckGrid.GetComponent<UnfixedGrid>().Add(obj, luckInst.Height);
                    }

                    luckGrid.GetComponent<UnfixedGrid>().Reposition();
                }
            }
        }

        /// <summary>
        ///  填充天赋数据
        /// </summary>
        /// 

        List<GameObject> tanlentLs = new List<GameObject>();
        private void FillTalentData(OrderDictionary<string,UITalent> tanlent)
        {
            if (module4.activeSelf)
            {
                if (tanlent != null && tanlent.Count > 0)
                {
                    if (tanlentLs.Count > 0)
                    {
                        foreach (var obj in tanlentLs)
                        {
                            GameObject.DestroyImmediate(obj);
                        }

                        tanlentLs.Clear();
                    }

                    talentGrid.GetComponent<UnfixedGrid>().ResetGrid();

                    const int topHeight = 49;

                    module4Height = topHeight;

                    int count = 0;
                    //int i = 0;
                    foreach (var kvp in tanlent)
                    {
                        if (kvp.data.talentLevel == "0" ) continue;

                        GameObject obj = GameObject.Instantiate(talentTemplete) as GameObject;
                        obj.SetActive(true);
                        tanlentLs.Add(obj);
                        obj.transform.SetParent(talentGrid.transform);
                        obj.transform.localScale = Vector3.one;
                        count++;

                        var tanlentInst = obj.GetComponent<UIHeroTalentTemplete>();

                        tanlentInst.Init(kvp,isMine);

                        talentGrid.GetComponent<UnfixedGrid>().Add(obj, tanlentInst.Height);

                        module4Height += talentGrid.GetComponent<UnfixedGrid>().Padding;
                        module4Height += tanlentInst.Height;
                    }

                    talentGrid.GetComponent<UnfixedGrid>().Reposition();
                }
            }
        }

        /// <summary>
        /// 填充hero的描述
        /// </summary>
        private void FillHeroDescribeData(string str)
        {
            heroDescribeText.GetComponent<UILabel>().text = "　　"+str;
        }

        /// <summary>
        /// 填充远征数据
        /// </summary>
        private void FillExpeditionData()
        {
            var str = hero.heroData.expeditionSkill;
            var sss = str.Split(new char[1] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);
            var str0 = "";
            foreach (var it in sss)
            {
                var kill = TableTextBlo.GetText("name_" + it);
                str0 = ";" + kill;
            }
            if (str.Length > 1)
                expeditionLabel.text = str0.Substring(1);
            else
                expeditionLabel.text="";
        }

        public void Close()
        {
            string strIcon = hero.heroData.iconName.Replace("hero_icon_", "hero_2d_");
            AssetLoadHelper.Instance.UnloadBundle("hero2d/" + strIcon);
        }
    }


}
